package org.example.loanapproval;

import org.camunda.bpm.dmn.engine.DmnDecisionTableResult;
import org.camunda.bpm.engine.DecisionService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.spring.boot.starter.annotation.EnableProcessApplication;
import org.camunda.bpm.spring.boot.starter.event.PostDeployEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.event.EventListener;

import java.util.logging.Level;
import java.util.logging.Logger;

@SpringBootApplication
@EnableProcessApplication
public class WebappExampleProcessApplication {

    protected final static Logger LOGGER = Logger.getLogger(WebappExampleProcessApplication.class.getName());

    public static void main(String... args) {
        SpringApplication.run(WebappExampleProcessApplication.class, args);
    }

    @Autowired
    private RuntimeService runtimeService;

    @EventListener
    private void processPostDeploy(PostDeployEvent event) {
        runtimeService.startProcessInstanceByKey("loan-approval");

        DecisionService decisionService = event.getProcessEngine().getDecisionService();

        VariableMap variables = Variables.createVariables()
                .putValue("bmi", 20.0);

        DmnDecisionTableResult dmnDecisionTableResult = decisionService
                .evaluateDecisionTableByKey("bmi-classification", variables);
        String result = dmnDecisionTableResult.getSingleEntry();

        LOGGER.log(Level.INFO, "\n\nBMI Classification result is : {0}\n\n", result);

        DmnDecisionTableResult suggestionResult = decisionService
                .evaluateDecisionTableByKey("bmi-suggestion", variables);
        String suggestion = suggestionResult.getSingleEntry();

        LOGGER.log(Level.INFO, "\n\nBMI Classification suggestion is : {0}\n\n", suggestion);
    }
}
